package com.funtl.screw.common.gateway.version;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.funtl.screw.common.core.constant.CommonConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 路由
 *
 * @author Lusifer
 */
@Slf4j
@RequiredArgsConstructor
public class ServiceRouteLoadBalancerImpl implements ServiceRouteLoadBalancer {

    private final DiscoveryClient discoveryClient;

    /**
     * 根据serviceId 筛选可用服务
     *
     * @param serviceId 服务ID
     * @param request   当前请求
     * @return ServiceInstance
     */
    @Override
    public ServiceInstance choose(String serviceId, ServerHttpRequest request) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);

        // 注册中心无实例 抛出异常
        if (CollUtil.isEmpty(instances)) {
            log.warn("No instance available for {}", serviceId);
            throw new NotFoundException("No instance available for " + serviceId);
        }
        // 获取请求version，无则随机返回可用实例
        String reqVersion = request.getHeaders().getFirst(CommonConstants.VERSION);
        if (StrUtil.isBlank(reqVersion)) {
            return instances.get(RandomUtil.randomInt(instances.size()));
        }

        List<ServiceInstance> instancesMachList = instances.stream().filter(s -> StrUtil.equalsIgnoreCase(reqVersion, s.getMetadata().get(CommonConstants.VERSION))).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(instancesMachList)) {
            return instancesMachList.get(RandomUtil.randomInt(instancesMachList.size()));
        }
        return instances.get(RandomUtil.randomInt(instances.size()));
    }

}
